<script setup>
import { useProductApi } from '/@/api/product';
const { getProdById, getProdList } = useProductApi();

const props = defineProps({
	modelValue: {
		type: Number,
	},
	productName: {
		type: String,
	},
});
const emit = defineEmits(['update:modelValue', 'update:productName', 'update:prodInfo']);
const selected = computed({
	get: () => props.modelValue,
	set: () => {},
});
const options = ref([]);
const loading = ref(false);
async function remoteMethod(query) {
	try {
		let params = {
			current: 1,
			pageSize: 99,
			publishStatus: 1,
			keyword: query === ' ' ? null : query,
		};
		loading.value = true;
		let res = await getProdList(params);
		loading.value = false;
		if (res.code !== 200) return;
		options.value = res.data.data;
	} catch (error) {
		loading.value = false;
	}
}
function change(val) {
	emit('update:modelValue', val);
	const optionHasTarget = options.value.find((item) => item.id === val) || {};
	emit('update:productName', optionHasTarget.name);
	emit('update:prodInfo', optionHasTarget);
}
//获取选项回显
async function getOption() {
	if (!props.modelValue) return;
	const optionHasTarget = options.value.find((item) => item.id === props.modelValue);
	if (optionHasTarget) return;
	loading.value = true;
	let res = await getProdById(props.modelValue);
	loading.value = false;
	if (res.code !== 200) return;
	options.value = [res.data];
}
watchEffect(getOption);
</script>
<template>
	<div class="ProdSelect">
		<el-select
			v-model="selected"
			filterable
			remote
			reserve-keyword
			placeholder="请输入关键词"
			clearable
			:loading="loading"
			:remote-method="remoteMethod"
			@change="change"
			v-bind="$attrs"
		>
			<el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" style="max-width: 230px"> </el-option>
		</el-select>
	</div>
</template>
<style lang="scss" scoped>
.ProdSelect {
	:deep(.el-input__validateIcon) {
		display: none;
	}
}
</style>
